package com.jd.platform.sample4.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 以下是获取key名的集合
 */
public interface RedisKey<T> {
    String getPojo();

    String getIdName();

    default String GetKeyById(String attribute,long id) {
        return String.format("%s:%s:%s", this.getPojo(), attribute, id);
    }

    default List<String> GetKeysById(Object object) throws Exception {
        if (object instanceof List) {
            return getKeysByIds((List<Object>) object);
        } else {
            if (object instanceof Long) {
                return getKeysById((Long) object);
//        } else if(object instanceof Produce) {
            } else {
                return getKeysById((T) object);
            }
        }
    }

    default List<String> getKeysById(T obj) throws Exception {
        List<String> keys = new ArrayList<>();
        List<String> attributes = AttributeUtil.getAttributeNames(obj.getClass()); //属性名集合
        attributes.remove(getIdName()); //不需要id，因为不需要用单独的键值对去存储在redis中
        long id = (long) AttributeUtil.getAttributeValue(obj, "id");

        for (int i = 0; i < attributes.size(); i++) {
            String attribute = attributes.get(i);
            keys.add(String.format("%s:%s:%s", this.getPojo(), attribute, id)); //尾部加入
        }
        return keys;
    }

    default List<String> getKeysById(long id) throws Exception {
        List<String> keys = new ArrayList<>();
        T obj = null;
        List<String> attributes = AttributeUtil.getAttributeNames(obj.getClass()); //属性名集合
        attributes.remove(getIdName()); //不需要id，因为不需要用单独的键值对去存储在redis中

        for (int i = 0; i < attributes.size(); i++) {
            String attribute = attributes.get(i);
            keys.add(String.format("%s:%s:%s", this.getPojo(), attribute, id)); //尾部加入
        }
        return keys;
    }

    default List<String> getKeysByIds(List<Object> objects) throws Exception {
        List<String> keys = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            if (objects.get(0) instanceof Long) {
                long id = (long) objects.get(i);
                List<String> pre = getKeysById(id);
                keys.addAll(pre);
            } else {
                T produce = (T) objects.get(i);
                List<String> pre = getKeysById(produce);
                keys.addAll(pre);
            }
        }
        return keys;
    }
}
